package xin.nick.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import xin.nick.common.util.MyAssert;
import xin.nick.service.IFileService;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author Nick
 * @since 2022/2/10
 */
@Primary
@Slf4j
@Service
public class LocalFileServiceImpl implements IFileService {

    /**
     * 配置的本地保存路径
     */
    @Value("${nick.file-upload.path}")
    private String localSavePath;

    /**
     * 配置的上传文件请求目录
     */
    @Value("${nick.file-upload.request-path}")
    private String fileRequestPath;

    /**
     * 项目地址
     */
    @Value("${nick.project-url}")
    private String projectUrl;


    @Override
    public String uploadFile(MultipartFile file) {
        // 获取到文件
        // 将文件保存到指定目录
        // 返回文件名

        // 原始文件名,取出文件后缀
        String originalFilename = file.getOriginalFilename();
        String[] arr = originalFilename.split("\\.");
        String suffix = arr[arr.length - 1];

        // 需要保存的文件名, 带上日期
        String fileName = IdUtil.fastSimpleUUID() + "." + suffix;

        // 目录带上日期
        LocalDateTime now = LocalDateTime.now();
        String dateFolder = now.getYear() +  "/" + now.getMonthValue() + "/" + now.getDayOfMonth();

        // 没有目录则创建
        File folderFile = new File(localSavePath + dateFolder);
        if (!folderFile.exists()) {
            folderFile.mkdirs();
        }

        // 写到文件
        String finalFileName =localSavePath + dateFolder + "/" + fileName;
        File finalFile = new File(finalFileName);

        // 写出文件
        try {
            FileUtil.writeBytes(file.getBytes(), finalFile);
        } catch (IOException e) {
            log.error("普通文件上传出错:" , e);
            MyAssert.throwException("普通文件上传出错");
        }

        String resultName = projectUrl +  fileRequestPath + "/" + dateFolder + "/" + fileName;
        return resultName;
    }
}
